#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author:Gwong Zaak Liu
@interpreter version:python 3.8.13
@file:  main.py
@time:  2022/10
"""
import re
import requests
from tqdm import trange

import __init__


def ReadFile(file_name):
    with open(file_name, "r", encoding='utf8') as f:
        return f.read()


def M3u8Filter(content):
    pattern = re.compile('[a-zA-z]+://[^\s]*.m3u8')
    items = re.findall(pattern, content)
    for item in items:
        return item


# 返回True可播放，false不可播放
def Discern(url):
    try:
        with requests.URLRequired(url) as file:
            if file.status != 200:
                return False
            else:
                return True
    except (ValueError, ArithmeticError):
        return False


# 写入内容到txt文件
def WriteFile(content, txtFileName):
    with open(txtFileName, 'a', encoding="utf-8") as file:
        file.write(content)


if __name__ == "__main__":
    #读取源文件
    str_item = ReadFile('../input.m3u')
    # 按行分割
    list_item = str_item.split('\n')
    # 写入开头
    WriteFile('#EXTM3U\n', "../AfterTestByPython.m3u")
    # 有效链接数
    EffectiveNumber = 0
    # 遍历每行
    for i in trange(len(list_item)):
        m3u8URL = M3u8Filter(list_item[i])
        # txt文件内的该行包含.m3u8文件
        if m3u8URL is not None:
            # print("testing %s" % m3u8URL)

            # 逐行检测request.response状态码，检测是否可用
            resCode = __init__.TestResponseCode(m3u8URL)
            # 状态码为200的才能使用
            if resCode == '<Response [200]>':
                EffectiveNumber += 1
                # print(list_item[i - 1])
                print('\ninput文件内链接的有效率: {:.1f}%'.format(EffectiveNumber/i*100))
                WriteFile(str(list_item[i - 1]), "../AfterTestByPython.m3u")
                WriteFile('\n', "../AfterTestByPython.m3u")

                # print(m3u8URL)
                WriteFile(str(m3u8URL), "../AfterTestByPython.m3u")
                WriteFile('\n', "../AfterTestByPython.m3u")
